import React, {Component} from 'react';
import './index.less';
import Header from '../components/Header';
import HROrgReger from '../../../../hrpub/common/components/referSearch/org';
import proFetch from '../../../public/functions/project-fetch';
import QuerySettingsResults from '../components/QuerySettingsResults'
import toggleModal from "./functions/toggleModalVisible";
import SearchSet from '../components/SearchSet'
import ManageScopeSet from '../components/ManageScopeSet'
import SearchModal from '../components/SearchModal'
import {base, toast} from 'nc-lightapp-front';
import ConfirmModal from '../components/ConfirmModal'

import {getAppPageConfig} from 'src/hrpub/common/utils/utils';

const {NCTabs} = base;
const NCTabPane = NCTabs.NCTabPane;


class HomePage extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.form('card1', 'card2', 'card3');
            props.use.editTable('list1', 'managescopebrowselist', 'managescopesettingslist');
        }
        // 示例为hrhi员工管理范围的appcode
        // this.appConfig = {
        //     pagecode: '600710A0p',
        //     appcode: '600710A0'
        // };
        this.appConfig = {
            pagecode: getAppPageConfig().pagecode,
            appcode: getAppPageConfig().appcode
        };

        this.state = {//构造函数是唯一能够初始化 this.state 的地方。
            json: {},//多语
            flagBut: true,
            context: {},
            activeKey: 1,//table的key
            humanResourceOrganizationValue: {},//人力资源组织选中的值
            searchModalVisible: false, // 管理范围浏览查询弹窗的显示隐藏
            searchModalSetting: false,//管理范围查询弹框显示隐藏
            scopeSetVisible: false,//管理范围设置弹框显示隐藏
            searchVisible: false,//条件选择搜素弹框显示隐藏
            isEdit: false,//是否是编辑状态
            showCancelModal: false,//取消确认弹框显示隐藏
            queryOid: '',//查询区组件id
            showDeleteConfirmModal: false,//删除确认弹框显示隐藏
            searchSetOldData: {},//显示查询设置数据
            getQuerySettingsResultsOldData: {},//查询设置结果数据
            pageHeight: ''
        };

        this.getTemplateData = this.getTemplateData.bind(this);
        this.handleHumanOrgTreeChange = this.handleHumanOrgTreeChange.bind(this);
        this.tabChange = this.tabChange.bind(this);

        this.deleteOperation = this.deleteOperation.bind(this);
        this.addOperation = this.addOperation.bind(this);
        this.editOperation = this.editOperation.bind(this);
        this.searchOperation = this.searchOperation.bind(this);
        this.saveOperation = this.saveOperation.bind(this);
        this.cancelOperation = this.cancelOperation.bind(this);
        this.refreshOperation = this.refreshOperation.bind(this);
        this.toggleModal = this.toggleModal.bind(this);
        this.updateMainTableData = this.updateMainTableData.bind(this);
        this.getManageScope = this.getManageScope.bind(this);
        this.getManageScopeView = this.getManageScopeView.bind(this);
        this.dbClickRow = this.dbClickRow.bind(this);
        this.clickHandle = this.clickHandle.bind(this);
        this.sureCancelModal = this.sureCancelModal.bind(this);
        this.sureDeleteOperation = this.sureDeleteOperation.bind(this);
        this.getSearchData = this.getSearchData.bind(this);
        this.getSearchSetOldData = this.getSearchSetOldData.bind(this);
        this.getQuerySettingsResultsOldData = this.getQuerySettingsResultsOldData.bind(this);
        this.getPageHeight = this.getPageHeight.bind(this)
    }

    componentDidMount() {
        window.location.hash = '#ifr?page=20190820qiaoshic'
        if (!('remove' in Element.prototype)) {
            Element.prototype.remove = function () {
                if (this.parentNode) {
                    this.parentNode.removeChild(this);
                }
            }
        }
        let callback = (json, status, inlt) => {
            if (status) {
                this.setState({json, inlt}, () => {
                    this.refs.ManageScopeSet.getLanguage(json)
                    this.refs.QuerySettingsResults.getLanguage(json)
                    this.refs.SearchSet.getLanguage(json)
                    this.getPageHeight()
                })//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({moduleId: 'hi6007', domainName: 'hrhi', callback})
        this.getTemplateData();
    }

    getTemplateData() {
        const {createUIDom, meta, button} = this.props;

        createUIDom(this.appConfig, (data = {}) => {
            this.setState({
                context: data.context,
                queryOid: data.template.managescopequery.oid,
                flagBut: false
            });
            meta.setMeta(data.template || {});
            button.setButtons(data.button || {});
            button.setButtonVisible({cancel: false, save: false, reset: false})//默认设置
            button.setButtonDisabled({edit: true, delete: true, add: true, query: true, refresh: true})
        });
    }

    getSearchData(data) {
        let historyData = [], pk_list = [];
        let searchResultData = this.props.editTable.getAllRows('list1');
        searchResultData.forEach((v, k) => {
            pk_list.push(v.values.pk_psnjob.value)
        })
        proFetch({
            url: '/nccloud/hrjf/managescope/ManageScopePsnQueryAction.do',
            body: {
                pk_list: pk_list,
                ...data
            },
        }).then((res) => {
            if (res.success) {
                if (res.data.list1) {
                    historyData = res.data.list1;
                    let newData = JSON.parse(JSON.stringify(historyData))
                    newData.rows = searchResultData.concat(historyData.rows)
                    this.props.editTable.setTableData('list1', newData)

                }
            }
        });
    }

    dbClickRow(record, index, props, e) {
        if (this.state.isEdit) {//编辑状态
            this.props.editTable.setStatus('managescopesettingslist', 'edit');
            let unEditBox = [];
            let managescopesettingslist = this.props.editTable.getAllRows('managescopesettingslist');
            let checkedManagescopesettingslist = this.props.editTable.getCheckedRows('managescopesettingslist');
            managescopesettingslist && managescopesettingslist.forEach((v, k) => {
                if (v.rowid != checkedManagescopesettingslist[0].data.rowid) {
                    unEditBox.push(v.rowid)
                }
            })
            this.props.editTable.setEditableRowByRowId('managescopesettingslist', unEditBox, false)
        }
    }

    clickHandle(props, moduleId, record, index) {
    }

    getManageScope(type) {//获取员工管理范围设置表单数据
        const {form} = this.props;
        let searchSetOldData = this.state.searchSetOldData.rows && this.state.searchSetOldData.rows[0].values || {}
        let postData = {
            funcType: 2,//1：组织管理范围 2：员工管理范围
            target: this.state.humanResourceOrganizationValue.refpk,//人力资源组织
            sourcer: type == 'refresh' ? searchSetOldData.sourcer && searchSetOldData.sourcer.value : form.getFormItemsValue('card1', 'sourcer').value,//管理对象
            sourceentity: '17cd227d-79ff-44a1-b6cf-13026ead6983',//管理对象类型
            pk_associateattr: type == 'refresh' ? searchSetOldData.busiregion && searchSetOldData.busiregion.value : form.getFormItemsValue('card1', 'busiregion').value,//管理业务
        };
        proFetch({
            url: '/nccloud/hrjf/managescope/QueryManageScopeAction.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                if (res.data && res.data.managescopesettingslist) {
                    this.updateMainTableData(res.data.managescopesettingslist, 1);
                } else {
                    this.props.editTable.setTableData('managescopesettingslist', {rows: []})
                }
            }
        });

    }

    getManageScopeView(type) {//获取员工管理范围浏览表单数据
        const {form} = this.props;
        let querySetOldData = this.state.getQuerySettingsResultsOldData.rows && this.state.getQuerySettingsResultsOldData.rows[0].values || {};
        let postData = {
            funcType: 2,//1组织，2人员
            param_bu: type == 'refresh' ? querySetOldData.bu && querySetOldData.bu.value : form.getFormItemsValue('card2', 'bu').value,//组织主键
            param_busiregion: type == 'refresh' ? querySetOldData.busiregion && querySetOldData.busiregion.value : form.getFormItemsValue('card2', 'busiregion').value,//业务范围主键
            param_dept: type == 'refresh' ? querySetOldData.dept && querySetOldData.dept.value : form.getFormItemsValue('card2', 'dept').value,//部门主键
            param_hrorg: type == 'refresh' ? querySetOldData.target && querySetOldData.target.value : form.getFormItemsValue('card2', 'target').value,//人力资源组织主键
            param_job: type == 'refresh' ? querySetOldData.job && querySetOldData.job.value : form.getFormItemsValue('card2', 'job').value,//职务主键
            param_post: type == 'refresh' ? querySetOldData.post && querySetOldData.post.value : form.getFormItemsValue('card2', 'post').value,//岗位主键
            param_psn: type == 'refresh' ? querySetOldData.psn && querySetOldData.psn.value : form.getFormItemsValue('card2', 'psn').value,//（人员）工作记录主键
        };
        proFetch({
            url: '/nccloud/hrjf/managescope/ManageScopeQuery2Action.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                if (res.data && res.data.managescopebrowselist) {
                    this.updateMainTableData(res.data.managescopebrowselist, 2);
                } else {
                    this.props.editTable.setTableData('managescopebrowselist', {rows: []})
                }

            }
        });
    }

    updateMainTableData(data, index, type) {//更新table数据
        let oldTableData = index == 1 ? this.props.editTable.getAllRows('managescopesettingslist') : this.props.editTable.getAllRows('managescopebrowselist');
        let newData = {};
        if (type == 'add') {//新增时更新table叠加
            let tableData = oldTableData.concat(data.rows || [])
            newData = JSON.parse(JSON.stringify(data));
            newData.rows = tableData;
        } else {
            newData = data
        }
        index == 1 ? this.props.editTable.setTableData('managescopesettingslist', newData) : this.props.editTable.setTableData('managescopebrowselist', newData)
        if (data.rows.length) {
            this.props.button.setButtonDisabled({edit: false, delete: false, refresh: false})

        }
    }

    handleHumanOrgTreeChange(value) {
        setTimeout(() => {
            this.props.editTable.setTableData('managescopesettingslist', {rows: []})
            this.props.editTable.setTableData('managescopebrowselist', {rows: []})
            if (value.refpk) {
                this.props.button.setButtonDisabled({edit: true, delete: true, add: false, query: false, refresh: true})
            } else {
                this.props.button.setButtonDisabled({edit: true, delete: true, add: true, query: true, refresh: true})
            }
            this.setState({humanResourceOrganizationValue: value});
        }, 0);

    }

    tabChange(activeKey) {//切换标签
        this.setState({
            activeKey
        })
        if (activeKey == 1) {//管理范围设置
            if (!this.state.isEdit) {//非编辑状态
                this.props.button.setButtonVisible({add: true, edit: true, delete: true, refresh: true})
                if (!this.props.button.getButtonDisabled('edit')) {
                    this.props.button.setButtonDisabled({refresh: false})
                }
                if (!this.state.humanResourceOrganizationValue.refname) {
                    this.props.button.setButtonDisabled({query: true})
                }
            } else {

                this.props.button.setButtonVisible({save: true, cancel: true, query: false, refresh: false})
            }
        } else {//管理范围浏览
            this.props.button.setButtonVisible({
                add: false,
                edit: false,
                delete: false,
                save: false,
                cancel: false,
                query: true,
                refresh: true
            })
            this.props.button.setButtonDisabled({query: false, refresh: true})
            if (this.props.editTable.getAllRows('managescopebrowselist').length) {
                this.props.button.setButtonDisabled({refresh: false})
            }
            if (!this.state.humanResourceOrganizationValue.refname) {
                this.props.button.setButtonDisabled({query: true})
            }
        }
    }

    // 新增数据弹窗
    addOperation() {
        this.setState({
            scopeSetVisible: true
        });
    }

    editOperation() {
        let selectData = this.props.editTable.getCheckedRows('managescopesettingslist') || [];
        if (selectData.length > 1) {//选择某行
            toast({
                color: 'warning',
                content: this.state.json['hi6007-000248'] //请只选择一条数据
            });
        } else if (selectData.length == 1) {
            this.props.button.setButtonVisible({
                save: true,
                cancel: true,
                add: false,
                edit: false,
                delete: false,
                query: false,
                refresh: false
            })

            this.props.editTable.setAllCheckboxAble('managescopesettingslist', false)
            // this.props.editTable.setStatus('managescopesettingslist', 'edit');
            this.setState({
                isEdit: true
            }, () => {
                this.dbClickRow()
            })

        } else {
            toast({
                color: 'warning',
                content: this.state.json['hi6007-000249'] //请选中要修改的数据
            });
        }

    }

    deleteOperation() {
        let selectData = this.props.editTable.getCheckedRows('managescopesettingslist') || [];
        if (selectData.length) {
            this.setState({
                showDeleteConfirmModal: true
            })
        } else {
            toast({
                color: 'wrining',
                content: this.state.json['hi6007-000164'] //请选择要删除的数据
            });
        }

    }

    sureDeleteOperation() {//删除数据
        let selectData = this.props.editTable.getCheckedRows('managescopesettingslist') || [];
        let selectIndexArr = [], rows = [];
        selectData.forEach((v, k) => {
            selectIndexArr.push(JSON.stringify(v.index))
            delete v.data.values.attrs;
            rows.push(v.data)
        })

        let postData = {
            model: {
                rows: rows
            },
            indexs: selectIndexArr,
        };
        proFetch({
            url: '/nccloud/hrjf/managescope/ManageScopeDeleteLineAction.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                this.setState({
                    showDeleteConfirmModal: false
                }, () => {
                    let deleteDataIndex = [];
                    selectData.forEach((v, k) => {
                        deleteDataIndex.push(v.index)
                    })
                    this.props.editTable.deleteTableRowsByIndex('managescopesettingslist', deleteDataIndex, true);
                })
            }
        }, (err) => {
            this.setState({
                showDeleteConfirmModal: false
            })
        });
    }

    searchOperation() {
        if (this.state.activeKey == 1) {//管理范围设置
            this.setState({
                searchModalSetting: true
            })
            this.props.form.setFormStatus('card1', 'edit')
            this.props.form.setFormItemsValue('card1',
                {
                    'target': {value: '0', display: this.state.humanResourceOrganizationValue.refname},
                    'sourceentity': {value: '17cd227d-79ff-44a1-b6cf-13026ead6983', display: '人员',},
                })


        } else {//管理范围浏览
            this.setState({
                searchModalVisible: true
            });
            this.props.form.setFormStatus('card2', 'edit')
            //产品要求去掉人力资源组织默认数据，做成可选
            /*this.props.form.setFormItemsDisabled('card2', {'post': false})
            this.props.form.setFormItemsValue('card2', {
                'target': {value: '0', display: this.state.humanResourceOrganizationValue.refname},
            })*/
        }
    }

    saveOperation() {//保存数据
        let selectRowData = this.props.editTable.getCheckedRows('managescopesettingslist') || [];
        let selectAttrs = [], selectRowArr = [];
        if (selectRowData.length) {
            if (selectRowData[0].data.values.attr_PSNDOC00000000000000.value) {
                selectAttrs.push('PSNDOC00000000000000')
            }
            if (selectRowData[0].data.values.attr_PSNPACT0000000000000.value) {
                selectAttrs.push('PSNPACT0000000000000')
            }
            if (selectRowData[0].data.values.attr_SALARY00000000000000.value) {
                selectAttrs.push('SALARY00000000000000')
            }
        }
        selectRowData[0].data.values.sourcer.value = selectRowData[0].data.values.sourcename.value
        delete selectRowData[0].data.values.attrs;
        selectRowArr.push(selectRowData[0].data)
        let postData = {
            attrs: selectAttrs,//选中的多选框
            index: selectRowData[0].index,//当前行数
            model: {
                areacode: 'managescopesettingslist',
                rows: selectRowArr
            }
        };
        let dataList = this.props.editTable.getAllRows('managescopesettingslist')
        this.props.editTable.checkRequired('managescopesettingslist', dataList)
        if (!postData.model.rows[0].values.sourcename.display || !postData.model.rows[0].values.target.display) {
            return
        }

        proFetch({
            url: '/nccloud/hrjf/managescope/ManageScopeSaveAction.do',
            body: postData,
        }).then((res) => {
            if (res.success) {
                toast({
                    color: 'success',
                    content: this.state.json['hi6007-000000'] //保存成功
                });
                this.setState({
                    isEdit: false
                })
                this.props.editTable.cancelEdit('managescopesettingslist');
                this.props.button.setButtonVisible({
                    save: false,
                    cancel: false,
                    add: true,
                    edit: true,
                    delete: true,
                    query: true,
                    refresh: true
                })
                this.getManageScope('refresh');
            }
        });
    }

    cancelOperation() {
        this.setState({
            showCancelModal: true
        })
    }

    refreshOperation() {
        if (this.state.activeKey == 1) {
            this.getManageScope('refresh')
        } else {
            this.getManageScopeView('refresh')
        }
    }

    getSearchSetOldData(data) {
        this.setState({
            searchSetOldData: data
        })
    }

    getQuerySettingsResultsOldData(data) {
        this.setState({
            getQuerySettingsResultsOldData: data
        })
    }

    toggleModal(type, visible) {
        return toggleModal.call(this, type, visible);
    }

    sureCancelModal() {//确认取消
        this.props.button.setButtonVisible({
            cancel: false,
            save: false,
            add: true,
            delete: true,
            query: true,
            edit: true,
            reset: false,
            refresh: true
        })
        this.props.button.setButtonDisabled({edit: false, delete: false, add: false, query: false, refresh: false})
        this.setState({
            isEdit: false
        })
        this.props.editTable.cancelEdit('managescopesettingslist');
        this.setState({
            showCancelModal: false
        })

    }
        // 获取app高度
        getPageHeight() {
            if (window.getComputedStyle) {
                let height = window.getComputedStyle(document.getElementById('app')).height.replace('px', '');
    
                this.setState({
                    pageHeight: height
                });
            }
        }

    render() {
        const {
            editTable,
        } = this.props;
        const {
            activeKey,
            searchModalVisible,
            searchModalSetting,
            scopeSetVisible,
            searchVisible,
            queryOid,
            flagBut,
            showCancelModal,
            showDeleteConfirmModal,
            pageHeight
        } = this.state;

        return (
            <div className="entry-personmanage-page">

                <div className="main-page">
                    <ConfirmModal
                        {...this.props}
                        titile={this.state.json['hi6007-000196']} //确认取消
                        text={this.state.json['hi6007-000009']} //是否确认要取消？
                        leftText={this.state.json['hi6007-000175']} //是
                        rightText={this.state.json['hi6007-000176']} //否
                        showModal={showCancelModal}
                        confirmOperation={this.sureCancelModal}
                        cancelOperation={this.toggleModal('showCancelModal', false)}
                    />
                    <ConfirmModal
                        {...this.props}
                        titile={this.state.json['hi6007-000200']} //确认删除
                        text={this.state.json['hi6007-000007']} //您确定要删除所选数据吗?
                        leftText={this.state.json['hi6007-000175']} //是
                        rightText={this.state.json['hi6007-000176']} //否
                        showModal={showDeleteConfirmModal}
                        confirmOperation={this.sureDeleteOperation}
                        cancelOperation={this.toggleModal('showDeleteConfirmModal', false)}
                    />
                    <SearchModal
                        {...this.props}
                        visible={searchVisible}
                        queryOid={queryOid}
                        getManageScope={this.getManageScope}
                        getSearchData={this.getSearchData}
                    />
                    <ManageScopeSet
                        {...this.props}
                        visible={scopeSetVisible}
                        onClose={this.toggleModal('scopeSetVisible', false)}
                        initData={this.state.humanResourceOrganizationValue}
                        updateMainTableData={this.updateMainTableData}
                        ref="ManageScopeSet"
                    />
                    <SearchSet
                        {...this.props}
                        visible={searchModalSetting}
                        onClose={this.toggleModal('searchModalSetting', false)}
                        initData={this.state.humanResourceOrganizationValue}
                        updateMainTableData={this.updateMainTableData}
                        getManageScope={this.getManageScope}
                        getSearchSetOldData={this.getSearchSetOldData}
                        ref="SearchSet"

                    />
                    <QuerySettingsResults
                        {...this.props}
                        visible={searchModalVisible}
                        onClose={this.toggleModal('searchModalVisible', false)}
                        initData={this.state.humanResourceOrganizationValue}
                        updateMainTableData={this.updateMainTableData}
                        getManageScopeView={this.getManageScopeView}
                        getQuerySettingsResultsOldData={this.getQuerySettingsResultsOldData}
                        ref="QuerySettingsResults"

                    />

                    <Header
                        {...this.props}
                        editOperation={this.editOperation}
                        flagBut={flagBut}
                        addOperation={this.addOperation}
                        deleteOperation={this.deleteOperation}
                        searchOperation={this.searchOperation}
                        saveOperation={this.saveOperation}
                        cancelOperation={this.cancelOperation}
                        refreshOperation={this.refreshOperation}
                        handleHumanOrgTreeChange={this.handleHumanOrgTreeChange}
                    />

                    {/* <div className="search-refer">
                        <HROrgReger
                            getOrgData={this.handleHumanOrgTreeChange}
                            orgVal={this.state.humanResourceOrganizationValue}
                        />
                    </div> */}
                    <div className="table-content">
                        <NCTabs navtype="turn"
                                contenttype="moveleft"
                                defaultActiveKey="1"
                                tabBarPosition="top"
                                onChange={this.tabChange}>
                            {/* 管理范围设置 */}
                            <NCTabPane tab={this.state.json['hi6007-000252']} key="1">
                                {
                                    editTable.createEditTable('managescopesettingslist', {
                                        showIndex: true,
                                        showCheck: true,
                                        // onRowDoubleClick: this.dbClickRow,
                                        onRowClick: this.clickHandle,
                                        adaptionHeight: true,
                                        height:  pageHeight - 115
                                    })
                                }

                            </NCTabPane>
                            {/* 管理范围浏览 */}
                            <NCTabPane tab={this.state.json['hi6007-000253']} key="2">
                                {
                                    editTable.createEditTable('managescopebrowselist', {
                                        showIndex: true,
                                        adaptionHeight: true,
                                        height:  pageHeight - 115
                                    })
                                }
                            </NCTabPane>
                        </NCTabs>

                    </div>

                </div>

            </div>
        );
    }
};

export default HomePage;